import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { forwardRef, useImperativeHandle } from "react";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { CreatePlatformWithCookieSchema } from "@/schemas";

export interface PlatformFormRef {
  onSubmit: () => void;
}

interface FormProps {
  handleSubmit: (values: FormData) => Promise<void>;
}

const PlatformCookieForm = forwardRef<PlatformFormRef, FormProps>(
  ({ handleSubmit }, ref) => {
    const form = useForm<z.infer<typeof CreatePlatformWithCookieSchema>>({
      resolver: zodResolver(CreatePlatformWithCookieSchema),
      defaultValues: {
        name: "京东",
        url: "",
        cookieName: "cookieuser1",
      },
    });

    useImperativeHandle(ref, () => ({
      onSubmit: async () => {
        try {
          const isValid = await form.trigger();
          if (isValid) {
            const values = form.getValues();
            const formData = new FormData();
            formData.append("file", values.file);
            formData.append("name", values.name);
            formData.append("url", values.url);
            formData.append("cookieName", values.cookieName);
            handleSubmit(formData);
          } else {
            console.log("Validation failed");
          }
        } catch (error) {
          console.error("Error during form submission:", error);
        }
      },
    }));

    return (
      <Form {...form}>
        <form className="space-y-6">
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center py-4 gap-4">
                <FormLabel htmlFor="id_platname" className="w-20">
                  平台名称
                </FormLabel>
                <FormControl>
                  <Input id="id_platname" {...field} className="w-60" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="url"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center py-4 gap-4">
                <FormLabel htmlFor="id_platurl" className="w-20">
                  访问地址
                </FormLabel>
                <FormControl>
                  <Input id="id_platurl" {...field} className="w-60" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="cookieName"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center py-4 text gap-4">
                <FormLabel htmlFor="id_cookiename" className="w-20">
                  Cookie名称
                </FormLabel>
                <FormControl>
                  <Input id="id_cookiename" {...field} className="w-60" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="file"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center py-4 gap-5">
                <FormLabel className="w-20" htmlFor="id_file">
                  Cookie文件
                </FormLabel>
                <FormControl>
                  <Input
                    id="id_file"
                    className="w-60"
                    type="file"
                    onChange={(e) => field.onChange(e.target.files?.[0])}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </form>
      </Form>
    );
  },
);

PlatformCookieForm.displayName = "PlatformCookieForm";
export { PlatformCookieForm };
